package com.xiang.api.service;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xiang.api.Util;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.util.List;

import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

  private boolean getFill(Annotation[] ar) {
    return getFill(ar, null);
  }

  private boolean getFill(Annotation[] ar, String fieldFill) {
    if (ar != null) {
      if (fieldFill == null) {
        fieldFill = "INSERT";
      }
      for (Annotation a : ar) {
        if (a.annotationType().getSimpleName().equals("TableField")) {
          return fieldFill.equals(((TableField) a).fill().toString());
        }
      }
    }
    return false;
  }

  /**
   * 新增时填充
   *
   * @param metaObject
   */
  @Override
  public void insertFill(MetaObject metaObject) {
    // createTime 对应实体属性名, 第二个参数需要填充的值
    // setInsertFieldValByName("createTime", LocalDateTime.now(), metaObject);
    Long t = Util.time();
    String n;
    Class<?> c;
    Object v;
    Field[] fieldInfos = metaObject.getOriginalObject().getClass().getDeclaredFields();
    for (Field field : fieldInfos) {
      try {
        n = field.getName();
        if (metaObject.getValue(n) == null && getFill(field.getAnnotations())) {
          c = field.getType();
          if (String.class.isAssignableFrom(c)) {
            v = "";
          } else if (Long.class.isAssignableFrom(c)) {
            v = n.toLowerCase().indexOf("time") < 0 ? Long.valueOf(0) : t;
          } else if (Integer.class.isAssignableFrom(c)) {
            v = Integer.valueOf(0);
          } else if (Character.class.isAssignableFrom(c)) {
            v = (char) 0;
          } else if (Float.class.isAssignableFrom(c)) {
            v = Float.valueOf(0);
          } else if (Double.class.isAssignableFrom(c)) {
            v = Double.valueOf(0);
          } else if (BigInteger.class.isAssignableFrom(c)) {
            v = BigInteger.valueOf(0);
          } else if (List.class.isAssignableFrom(c)) {
            v = "[]";
          } else {
            v = "";
          }
          this.fillStrategy(metaObject, n, v);
        }
      } catch (Exception e) {
      }
    }
    // v = 0L;
    // this.fillStrategy(metaObject, "readTime", v);
    return;
  }

  /**
   * 修改时填充
   *
   * @param metaObject
   */
  @Override
  public void updateFill(MetaObject metaObject) {
    // updateTime 对应实体属性名, 第二个参数需要填充的值
    // setUpdateFieldValByName("updateTime", LocalDateTime.now(), metaObject);
    Long t = Util.time();
    this.fillStrategy(metaObject, "changeTime", t);
  }
}
